package gui;

import gamehandlers.GameHandler;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.Timer;


/**
 * A Canvas to paint the game.
 * 
 * @author Yaqi Zhang, Seon Kang
 * 
 */
@SuppressWarnings("serial")
public class Canvas extends JComponent {
    private static final int ONE_SECOND = 1000;
    private static final int FRAMES_PER_SECOND = 25;
    private GameHandler myGameHandler;
    private int myLastKeyPressed;
    private Point myLastMouseLoc;
    private Timer myTimer;

    /**
     * @param size Size
     * @param gh GameHandler
     */
    public Canvas (Dimension size, GameHandler gh) {
        setPreferredSize(size);
        setGameHandler(gh);
        setInputListner();
        setTimer();
    }

    private void setTimer () {
        myTimer = new Timer(ONE_SECOND / FRAMES_PER_SECOND,
                new ActionListener() {
                    @Override
                    public void actionPerformed (ActionEvent e) {
                        update();
                    }
                });
    }

    @Override
    protected void paintComponent (Graphics pen) {
        myGameHandler.paint(pen);
    }

    /**
     * update game handler
     */
    public void update () {
        myGameHandler.update();
        repaint();
    }

    private void setInputListner () {
        KeyListener kl = new KeyAdapter() {
            @Override
            public void keyPressed (KeyEvent e) {
                myLastKeyPressed = e.getKeyCode();
            }

            public void keyReleased (KeyEvent e) {
                myLastKeyPressed = 0;
            }
        };
        MouseMotionListener mml = new MouseAdapter() {
            @Override
            public void mouseClicked (MouseEvent e) {
                myLastMouseLoc = e.getPoint();
            }
        };
    }

    /**
     * @return the key pressed by the player.
     */
    public int getUserKeyInput () {
        return myLastKeyPressed;
    }

    /**
     * @return the key pressed by the user.
     */
    public Point getUserMouseInput () {
        return myLastMouseLoc;
    }

    /**
     * @param gh GameHandler
     */
    public void setGameHandler (GameHandler gh) {
        myGameHandler = gh;
    }
}
